package simorg;

import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

class Log {
	enum DebugLevel {
		MOST, MORE, STANDARD, MINIMAL, NONE
	}

	static String s_buffer = "";

	static final DebugLevel MIN_LEVEL_STD_OUT = DebugLevel.NONE;

	static final DebugLevel MIN_LEVEL_FILE_OUT = DebugLevel.MOST;

	static final String LOG_FILE_NAME = "simorg.log";

	static void flush() {

		// write buffer to log file
		BufferedWriter logFile = null;
		try {
			logFile = new BufferedWriter(new FileWriter(LOG_FILE_NAME, true));
			logFile.write(s_buffer);
			logFile.close();
		} catch (final IOException ioex) {
			System.out.println("[Error writing to log file.]");
		}

		// clear the buffer
		s_buffer = "";
	}

	static String getDateTimeString() {
		final DateFormat dateFormat = new SimpleDateFormat(
				"MM/dd/yyyy HH:mm:ss");
		final Date date = new Date();
		return dateFormat.format(date);
	}

	static void initialize() {
		BufferedWriter logFile = null;
		try {
			logFile = new BufferedWriter(new FileWriter(LOG_FILE_NAME));
			logFile.write("Log created " + getDateTimeString() + "\n");
			logFile.close();
		} catch (final IOException ioex) {
			System.out.println("[Error creating log file.]");
		}

		System.out.println("Log created.");
	}

	static void write(final String a_msg) {
		write(a_msg, DebugLevel.STANDARD);
	}

	static void write(final String a_msg, final DebugLevel a_debugLevel) {

		// write to log file buffer
		if (a_debugLevel.ordinal() >= MIN_LEVEL_FILE_OUT.ordinal()) {
			s_buffer += a_msg;
		}

		// write to stdout
		if (a_debugLevel.ordinal() >= MIN_LEVEL_STD_OUT.ordinal()) {
			System.out.print(a_msg);
		}
	}

	static void writeLine() {
		writeLine("");
	}

	static void writeLine(final String a_msg) {
		writeLine(a_msg, DebugLevel.STANDARD);
	}

	static void writeLine(final String a_msg, final DebugLevel a_debugLevel) {
		write(a_msg + "\n", a_debugLevel);
	}
}
